import { Button, Form, Input, Result } from 'antd'
import FormItem from 'antd/lib/form/FormItem'
import React, { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { Link } from 'react-router-dom'
import { resetSignup, signup, SignupPayload } from '../../store/actions/auth.action'
import { AppState } from '../../store/reducers'
import { AuthState } from '../../store/reducers/auth.reducer'
import Layout from './Layout'

const Signup = () => {
  const authState = useSelector<AppState, AuthState>(state => state.auth)
  const dispatch = useDispatch()
  const onFinish = (value: SignupPayload) => {
    console.log('onFinish')
    console.log(value)
    dispatch(signup(value))
  }
  const [form] = Form.useForm()
  //1、auth状态更新并且注册成功的时候，清空表单
  useEffect(() => {
    if (authState.signup.loaded && authState.signup.success) {
      form.resetFields()
    }
  }, [authState])
  //2、显示注册成功信息，并在信息中包含跳转登录页面button
  const showSuccess = () => {
    if (authState.signup.loaded && authState.signup.success) {
      return (
        <Result
          title="注册成功"
          status="success"
          extra={[
            <Button type="primary">
              <Link to="/signin">登录</Link>
            </Button>
          ]}
        />
      )
    }

  }
  //3、显示注册失败信息
  const showError = () => {
    if (authState.signup.loaded && !authState.signup.success) {
      return (
        <Result
          title="注册失败"
          subTitle={authState.signup.message}
          status="warning"
        />
      )
    }
  }
  const signupForm = () => {
    return (
      <Form form={form} initialValues={{ name: '海燕', password: '123456', email: 'testemail@163.com' }} onFinish={onFinish}>
        <FormItem label="昵称" name="name">
          <Input />
        </FormItem>
        <FormItem label="密码" name="password">
          <Input.Password />
        </FormItem>
        <FormItem label="邮箱" name="email">
          <Input />
        </FormItem>
        <FormItem>
          <Button type="primary" htmlType="submit">注册</Button>
        </FormItem>
      </Form>

    )
  }
  //重置注册状态
  useEffect(()=>{
    return ()=>{
      dispatch(resetSignup())
    }
  },[])
  return (
    <Layout title="拉钩注册" subTitle="拉钩注册">
      {showSuccess()}
      {showError()}
      {signupForm()}
      </Layout>
  )
}

export default Signup